package org.example.chenniyrpcspingbootstarter.bootstrap;

import org.example.chenniyrpcspingbootstarter.annotation.RpcReference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import proxy.ProxyServiceFactory;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 服务消费者启动类
 * 作用：在Spring容器初始化bean后，自动为带有@RpcReference注解的字段注入RPC代理对象
 */
public class ConsumerBootStrap implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 获取bean的Class对象
        Class<?> beanClass = bean.getClass();
        // 遍历所有字段，查找带有@RpcReference注解的属性
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            RpcReference rpcReference = field.getAnnotation(RpcReference.class);
            if (Objects.nonNull(rpcReference)) {
                // 获取注解中指定的接口类型，若未指定则取字段类型
                Class<?> interfaceClass = rpcReference.interfaceClass();
                if (interfaceClass == void.class) {
                    interfaceClass = field.getType();
                }
                // 设置字段可访问
                field.setAccessible(true);
                // 生成代理对象并注入到字段
                Object proxy = ProxyServiceFactory.getProxy(interfaceClass);
                try {
                    field.set(bean, proxy);
                } catch (Exception e) {
                    throw new RuntimeException("为字段注入代理对象失败", e);
                } finally {
                    // 恢复字段可访问性
                    field.setAccessible(false);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
